package com.cloudinnov.controller.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.NotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cloudinnov.aop.SystemLog;
import com.cloudinnov.dao.EquipmentsDao;
import com.cloudinnov.logic.CarDetectorLogic;
import com.cloudinnov.logic.impl.CarDetectorLogicImpl;
import com.cloudinnov.model.CarDetectorData;
import com.cloudinnov.model.Equipments;
import com.cloudinnov.model.ExportData;
import com.cloudinnov.utils.JudgeNullUtil;
import com.cloudinnov.utils.POIUtils;

@Controller
@RequestMapping("/webapi/carDetector")
public class CarDetectorController extends BaseController
{
    @Autowired
    private CarDetectorLogic carDetectorLogic;
    
    @RequestMapping(value = "/select", method = RequestMethod.GET)
    public void select(HttpServletRequest request, HttpServletResponse response, CarDetectorData model)
        throws IOException
    {
        String returnData = "";
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> data = carDetectorLogic.selectDataByEquCodeToRedis(model.getEquipmentCode());
        if (data != null)
        {
            map.put("model", data);
            returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        }
        else
        {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().println(returnData);
    }
    
    @RequestMapping(value = "/report", method = RequestMethod.GET)
    public void report(HttpServletRequest request, HttpServletResponse response, CarDetectorData model,
        String startTime, String endTime, int type)
        throws IOException
    {
        String returnData = "";
        Map<String, String> params = new HashMap<String, String>();
        params.put(CarDetectorLogicImpl.KEY_EQUCODE, model.getEquipmentCode());
        params.put(CarDetectorLogicImpl.KEY_START_TIME, startTime);
        params.put(CarDetectorLogicImpl.KEY_END_TIME, endTime);
        Map<String, Object> map = carDetectorLogic.selectReportDataToMongoDB(type,params);
        map.put("equipCode", model.getEquipmentCode());
        returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        
        response.getWriter().println(returnData);
    }
    
    /**
     * 车检仪报表数据导出
     * 
     * @param request
     * @param response
     * @param model
     * @param startTime
     * @param endTime
     * @throws IOException
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @SystemLog(module = "车检仪管理", methods = "导出车检仪数据")
    public void export(HttpServletRequest request, HttpServletResponse response, Equipments model, String startTime,
        String endTime, String euqipmentName, int type)
        throws IOException
    {
    	
        Map<String, String> params = new HashMap<String, String>();
        params.put(CarDetectorLogicImpl.KEY_EQUCODE, model.getEquipmentCode());
        params.put(CarDetectorLogicImpl.KEY_START_TIME, startTime);
        params.put(CarDetectorLogicImpl.KEY_END_TIME, endTime);
        Map<String, Object> map = carDetectorLogic.selectReportDataToMongoDB(type, params);
        List<String> eqList = new ArrayList<String>();
        eqList.add(euqipmentName);
        eqList.add(model.getSectionName());
        eqList.add(model.getPileNo());
        ExportData exportData = new ExportData();
        Map<String, Object> models = (Map<String, Object>)map.get("model");
        List<Map<String, Object>> carData = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> carDatas = new ArrayList<Map<String, Object>>();
        if (type == 1)
        {// 年
        	carDatas = (List<Map<String, Object>>)models.get("year");
        	carData = getRankMongoData(carDatas);
        }
        else if (type == 2)
        {// 月
        	carDatas = (List<Map<String, Object>>)models.get("month");
            carData = getRankMongoData(carDatas);
        }
        else if (type == 3)
        {// 日
        	carDatas = (List<Map<String, Object>>)models.get("day");
            carData = getRankMongoData(carDatas);
        }
        else if (type == 4)
        {// 时
        	carDatas = (List<Map<String, Object>>)models.get("hour");
            carData = getRankMongoData(carDatas);
        }
        List<String> times = new ArrayList<String>();
        for (Map<String, Object> map2 : carData)
        {
            String time = (String)map2.get("time");
            times.add(time);
        }
        String timesTreand = null;
        if (JudgeNullUtil.iList(times))
        {
            if (times.size() == 1)
            {
                timesTreand = "时间范围：" + times.get(0) + "到" + times.get(0);
            }
            else
            {
                timesTreand = "时间范围：" + times.get(0) + "到" + times.get(times.size() - 1);
            }
            exportData.setTime(times);
        }
        if (JudgeNullUtil.iList(eqList) && JudgeNullUtil.iList(times))
        {
            POIUtils.exportExcel("车检仪数据", eqList, timesTreand, times, carData, response);
        }
    }
    
    /**
     * 
     * @Title: selectCarDetectorHistoryList
     * @Description: 车检仪导出数据（年月日时）
     * @param @param model
     * @param @param startTime
     * @param @param endTime
     * @param @param request
     * @param @param response       
     * @return void @throws
     */
    @RequestMapping(value = "/exports", method = RequestMethod.GET)
    @SystemLog(module = "车检仪管理", methods = "导出车检仪数据")
    public void selectCarDetectorHistoryList(Equipments model, String startTime, String endTime, String euqipmentName,
        HttpServletRequest request, HttpServletResponse response)
    {
        
        if (startTime == null)
        {
            throw new NotFoundException();
        }
        
        // 查询车检仪的数据
        Map<String, String> params = new HashMap<String, String>();
        params.put(CarDetectorLogicImpl.KEY_EQUCODE, model.getEquipmentCode());
        params.put(CarDetectorLogicImpl.KEY_START_TIME, startTime);
        params.put(CarDetectorLogicImpl.KEY_END_TIME, endTime);
        Map<String, Object> map = carDetectorLogic.selectReportDataToMongoDB(0, params);
        
        // 获取设备信息
        List<String> eqList = new ArrayList<String>();
        eqList.add(euqipmentName);
        eqList.add(model.getSectionName());
        eqList.add(model.getPileNo());
        
        map.put("eqList", eqList);
        
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        POIUtils.exportCarDataToExcel(map, response);
    }
    
    /**
	 * 把mongo的数据排序后返回
	 * @param mongoData 数据来源
	 * @return
	 */
	public List<Map<String, Object>> getRankMongoData(List<Map<String, Object>> mongoData){
		Collections.sort(mongoData, new Comparator<Map<String, Object>>() {
			public int compare(Map<String, Object> mongoData1, Map<String, Object> mongoData2) {
				String date1 = "";
				String date2 = "";
				date1 = mongoData1.get("time").toString();
				date2 = mongoData2.get("time").toString();
				return date1.compareTo(date2);
			}
		});
		return mongoData;
	}
    
}
